package org.com.Service.Impl;

import Entity.Blog;
import Entity.Community;
import cn.hutool.core.bean.BeanUtil;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.StorageClass;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.com.FeignClient.CommunityFeign;
import org.com.Mapper.BlogMapper;
import org.com.Service.IBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 277
 * @since 2025-09-23
 */
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private StringRedisTemplate redis;

    @Autowired
    private CommunityFeign communityFeign;


//    @Override
//    public String uploadFile(MultipartFile file, String content, String title) {
//        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
//
//        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//        EnvironmentVariableCredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
//        String buckedName = "bucket-soouth1";
//        String objectName = "south/southobject";
//        String region = "cn-chengdu";
//
//// 创建OSSClient实例。
//        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
//        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
//        OSS ossClient = OSSClientBuilder.create()
//                .endpoint(endpoint)
//                .credentialsProvider(credentialsProvider)
//                .clientConfiguration(clientBuilderConfiguration)
//                .region(region)
//                .build();
//
//
//        try {
//            //生成原文件名
//            String originalFilename = file.getOriginalFilename();
//            //截取字符串获取文件后缀
//            String FileEXtension = originalFilename.substring(originalFilename.lastIndexOf("."));
////生成新文件名
//            String newFileName = System.currentTimeMillis() + FileEXtension+System.currentTimeMillis();
//
//
//            // 创建元数据
//            ObjectMetadata metadata = new ObjectMetadata();
//            metadata.setContentType(file.getContentType());
//            metadata.setContentLength(file.getSize());
//            metadata.setHeader("OSSStorageClass", StorageClass.Standard.toString());
//
//            // 创建上传请求
//            PutObjectRequest putObjectRequest = new PutObjectRequest(
//                    buckedName,
//                    objectName,
//                    file.getInputStream(),
//                    metadata
//            );
//
//            // 上传文件
//            PutObjectResult result = ossClient.putObject(putObjectRequest);
//
//            // 生成访问URL
//            String fileUrl = "https://" + buckedName + ".oss-cn-chengdu.aliyuncs.com/" + objectName;
//
//            //当前用户
//            String user = redis.opsForValue().get("login:user:");
//
//
//            Blog blog = new Blog();
//            blog.setUser(Integer.valueOf(user));
//            blog.setOssName(newFileName);
//            blog.setType(file.getContentType());
//            blog.setTitle(title);
//            blog.setContent(content);
//            blog.setOssUrl(fileUrl);
//
//            this.save(blog);
//
//            Community community = new Community();
//            community.setUserId(Integer.valueOf(user));
//            community.setTitle(title);
//            community.setContent(content);
//            community.setLikeMember(0L);
//            community.setCommentMember(0L);
//            ResponseEntity<Community> save = communityFeign.save(community);
//            Community body = save.getBody();
//
//
//
//            Map<String, Object> communityMap = BeanUtil.beanToMap(body, false, true);
//// 转换为 String, String 类型
//            Map<String, String> commap = new HashMap<>();
//            for (Map.Entry<String, Object> entry : communityMap.entrySet()) {
//                if (entry.getValue() != null) {
//                    commap.put(entry.getKey(), entry.getValue().toString());
//                }
//            }
//            log.info("community:{}", body);
//
//            redis.opsForHash().putAll("community:" + body.getId(),
//                    commap);
//
//
//            log.info("上传成功");
//            return "上传成功";
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
//
//    }

    @Override
    public String uploadFile(MultipartFile file, String content, String title) {
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";

        EnvironmentVariableCredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
        String buckedName = "bucket-soouth1";
        String region = "cn-chengdu";

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String FileEXtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = System.currentTimeMillis() + FileEXtension;


            String objectName = "south/" + newFileName; // 重要：使用动态路径

            // 创建元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());
            metadata.setHeader("OSSStorageClass", StorageClass.Standard.toString());

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    buckedName,
                    objectName,
                    file.getInputStream(),
                    metadata
            );


            PutObjectResult result = ossClient.putObject(putObjectRequest);

            String fileUrl = "https://" + buckedName + ".oss-cn-chengdu.aliyuncs.com/" + objectName;

            String user = redis.opsForValue().get("login:user:");

            Blog blog = new Blog();
            blog.setUser(Integer.valueOf(user));
            blog.setOssName(newFileName);
            blog.setType(file.getContentType());
            blog.setTitle(title);
            blog.setContent(content);
            blog.setOssUrl(fileUrl); // 保存正确的URL

            this.save(blog);

            Community community = new Community();
            community.setUserId(Integer.valueOf(user));
            community.setTitle(title);
            community.setContent(content);
            community.setLikeMember(0L);
            community.setCommentMember(0L);
            ResponseEntity<Community> save = communityFeign.save(community);
            Community body = save.getBody();

            Map<String, Object> communityMap = BeanUtil.beanToMap(body, false, true);
            Map<String, String> commap = new HashMap<>();
            for (Map.Entry<String, Object> entry : communityMap.entrySet()) {
                if (entry.getValue() != null) {
                    commap.put(entry.getKey(), entry.getValue().toString());
                }
            }
            log.info("community:{}", body);

            redis.opsForHash().putAll("community:" + body.getId(), commap);

            log.info("上传成功，文件URL: {}", fileUrl);
            return "上传成功";
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {

            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    @Override
    public List<Blog> showblog() {
        String user = redis.opsForValue().get("login:user:");
        List<Blog> list = lambdaQuery().eq(Blog::getUser, user)
                .list();
        log.info("查询成功");
        return list;

    }

    @Override
    public boolean deleteWithCommunity(Integer id) {
        communityFeign.delete(id);
        return removeById(id);
    }
}
